<template>
  <div class="ky-container">
    <div @click="closeRight">
      <el-card shadow="hover" class="ky-card ky-card-xs ky-card-hdbg">
        <el-form
          :inline="true"
          class="m-t-1 apply-card ky-form-inline ky-form-inline-sm"
          label-width="80px"
        >
          <el-form-item label="医院名称">
            <el-select
              size="small"
              v-model="formData.hospitalCode"
              @change="handleChange('hospital')"
              placeholder="请选择医院"
              filterable
              allow-create
            >
              <el-option
                v-for="item in mx_hospitalList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查部门" prop="dep">
            <el-select
              style="width: 100%"
              size="small"
              v-model="formData.dep"
              @change="handleChange('dep')"
              placeholder="请选择"
              clearable
              multiple
              collapse-tags
              filterable
              allow-create
            >
              <el-option
                v-for="item in depOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型" prop="modality">
            <el-select
              style="width: 100%"
              size="small"
              v-model="formData.modality"
              placeholder="请选择"
              clearable
              multiple
              collapse-tags
              filterable
              allow-create
              @change="handleChange('modality')"
            >
              <el-option
                v-for="item in modalityOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="检查分组" prop="checkGroup">
            <el-select style="width:100%" size="small" v-model="formData.checkGroup" placeholder="请选择" clearable filterable multiple collapse-tags allow-create>
              <el-option
                v-for="item in checkGroupOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查机房" prop="checkRoom" allow-create>
            <el-select
              style="width: 100%"
              size="small"
              v-model="formData.checkRoom"
              placeholder="请选择"
              clearable
              multiple
              filterable
              allow-create
              collapse-tags
            >
              <el-option
                v-for="item in checkRoomOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查部位" prop="bigpart">
            <el-input
              size="small"
              placeholder="请输入"
              v-model="formData.bigpart"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="检查项目" prop="smallpart">
            <el-input
              size="small"
              placeholder="请输入"
              v-model="formData.smallpart"
              clearable
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="部位类型" prop="partType">
            <el-select
              style="width: 100%"
              size="small"
              v-model="formData.partType"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in partTypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="系数设置" prop="workCountType">
            <el-select
              style="width: 100%"
              size="small"
              v-model="formData.workCountType"
              placeholder="请选择"
              clearable
              allow-create
            >
              <el-option
                v-for="(item, index) in workCountTypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目属性" prop="itemProperty">
            <el-select
              style="width: 100%"
              size="small"
              filterable
              allow-create
              v-model="formData.itemProperty"
              multiple
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in itempropertyOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="注意事项" prop="examNoticeGroup">
            <el-select
              style="width: 100%"
              size="small"
              filterable
              allow-create
              v-model="formData.examNoticeGroup"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in examNoticeGroupOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="部位类型" prop="partType">
            <el-select
              style="width: 100%"
              size="small"
              v-model="formData.partType"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="(item, index) in partTypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="项目过滤" prop="filterType">
            <el-select
              style="width: 100%"
              size="small"
              v-model="formData.filterType"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="(item, index) in filterTypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="系数设置" prop="workCountType">
            <el-select
              style="width: 100%"
              size="small"
              v-model="formData.workCountType"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="(item, index) in workCountTypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <div class="flex flex-row align-center">
              <el-button
                type="primary"
                class="m-l-0"
                size="small"
                icon="el-icon-search"
                @click="search"
              >查询</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
      <div class="quickfilter-content ky-mt10">
        <el-card v-show="quickFilterStatus" shadow="hover" class="qf-sidebar ky-card ky-card-hdbg">
          <div class="content-title" style="line-height: 34px;">
            <span class="tit">快速查询</span>
            <i class="el-icon-arrow-left ky-fr ky-pointer ky-ft16 ky-fw600" style="margin-top: 8px;" @click="quickFilterStatus = false"></i>
          </div>
          <HospDepFilter
            ref="hospDepFilter"
            :hospital-code="formData.hospitalCode"
            @treeChange="treeChange"></HospDepFilter>
        </el-card>
        <el-card shadow="hover" class="qf-box ky-card ky-card-hdbg">
          <div class="content-title flex flex-row align-center">
            <i class="el-icon-arrow-right ky-pointer ky-ft16 ky-fw600" v-show="!quickFilterStatus" @click="quickFilterStatus = true"></i>
            <span class="tit">HIS部位列表</span>
            <el-button
              class="add-button"
              type="primary"
              size="small"
              @click.stop="getRightPanel(pageStatus.add)"
            ><i class="el-icon-plus icon"></i>新增部位</el-button
            >
            <el-upload
              action=""
              :auto-upload="false"
              accept=".xlsx, .xls"
              :show-file-list="false"
              :on-change="importExcel"
              size="small"
              style="display: inline-block; margin: 0 10px;"
            >
              <el-button size="small">Excel导入</el-button>
            </el-upload>
            <span class="span-click" @click="downLoadExcel">Excel模板下载</span>
            <div class="mar-l-10">
              <hisPartSort
                @refresh="search"
                :hospital-code="formData.hospitalCode"
                :config-visible.sync="configVisible"
                :table-data="tableData"
              />
            </div>
          </div>
          <el-table
            ref="table"
            :data="hisData"
            style="width: 100%"
            max-height="600"
            class="ky-table"
            border
            highlight-current-row
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              align="center"
              label="操作"
              :width="$hasPermission(['YJYY10002012']) ? 200 : 310"
              v-if="$hasPermission(['YJYY10002010', 'YJYY10002011'])"
            >
              <template slot-scope="scope">
                <div class="flex flex-row justify-center text-center">
                  <el-button
                    type="primary"
                    size="small"
                    v-permission="'YJYY10002010'"
                    @click.stop="bindCheckRoom(scope.$index, scope.row)"
                  ><i class="el-icon-circle-plus"></i> 绑定检查机房</el-button
                  >
                  <el-button
                    type="warning"
                    size="small"
                    v-permission="'YJYY10002011'"
                    @click.stop="handleEdit(scope.$index, scope.row)"
                  ><i class="el-icon-edit"></i> 编辑</el-button
                  >
                  <el-button
                    type="danger"
                    size="small"
                    @click.stop="handleDelete(scope.$index, scope.row)"
                    v-if="!$hasPermission(['YJYY10002012'])"
                  ><i class="el-icon-delete"></i> 删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="hospitalCode" label="医院名称" :formatter="frtHospCode" min-width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="dep" label="检查部门"></el-table-column>
            <el-table-column prop="checkGroup" label="检查分组" width="80" show-overflow-tooltip></el-table-column>
            <el-table-column prop="modality" label="设备类型"></el-table-column>
            <el-table-column prop="bigpart" label="检查部位"></el-table-column>
            <el-table-column prop="smallpart" label="检查项目" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="hisid" label="HIS部位代码" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="partModality" label="部位设备" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="templatePart" label="词库模板部位" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="workCount" label="系数" width="55"></el-table-column>
            <el-table-column prop="itemProperty" label="项目属性" min-width="160" show-overflow-tooltip></el-table-column>
            <el-table-column prop="itemCode" label="部位编码" min-width="160" show-overflow-tooltip></el-table-column>
            <!-- <el-table-column prop="filter" label="过滤检查项目" min-width="160">
              <template slot-scope="scope">
                <el-tag size="small" type="success" v-if="scope.row.filter">{{scope.row.filter}}</el-tag>
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="partType" label="省对照部位" min-width="160">
              <template slot-scope="scope">
                <el-tag size="small" type="success" v-if="scope.row.partType">开启</el-tag>
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="hisid" label="HIS部位代码" min-width="160"></el-table-column> -->
            <!-- <el-table-column prop="uisId" label="超声部位代码" min-width="160"></el-table-column> -->
            <el-table-column prop="itemName" label="省互认项目名称" min-width="160"></el-table-column>
            <el-table-column prop="examNoticeGroup" label="注意事项字典组" min-width="160"></el-table-column>
          </el-table>
          <paginationCont
            :total="totalCount"
            :page.sync="currentPage"
            :page-sizes="[10, 20, 30, 50, 300]"
            :limit.sync="pageSize"
            @pagination="fetchData"
          />
        </el-card>
      </div>
      <transition name="fade-form" mode="out-in">
        <div
          :class="{
            'toolBox-small': device !== 'mobile' && sidebar.opened,
            'toolBox-midul': device !== 'mobile' && !sidebar.opened,
            'toolBox-large': device == 'mobile',
            toolBox: true,
          }"
          v-show="showToolBox"
        >
          <div>
            <i class="el-icon-info icon blue-color"></i>
            <span
              class="toolBox-text"
            >已选择<span class="blue-color">{{multipleSelection.length}}</span
            >项</span
            >
            <span class="cancle-click" @click="cancleChoose">取消选择</span>
          </div>
          <div>
            <el-button
              type="primary"
              size="small"
              @click="setWorkOutTypeVisible"
            >批量设置部位系数</el-button>
            <el-button
              type="primary"
              size="small"
              @click="setCheckGroupVisible"
            >批量设置检查分组</el-button>
            <el-button
              type="primary"
              size="small"
              @click="setItemPropertyVisible"
            >批量设置项目属性字典组</el-button>
            <el-button
              type="primary"
              size="small"
              @click="setExamNoticeGroup"
            >批量设置注意事项字典组</el-button>
            <el-button
              type="primary"
              size="small"
              @click="setPartModality"
            >批量设置部位设备</el-button>
            <el-button
              type="primary"
              size="small"
              @click="setTemplatePart"
            >批量设置词库模板部位</el-button>
            <el-button
              type="danger"
              size="small"
              @click="batchDelete"
              v-if="!$hasPermission(['YJYY10002012'])"
            >批量删除</el-button>
          </div>
        </div>
      </transition>
    </div>
    <edit-dialog
      ref="editRoom"
      :hospital-code="formData.hospitalCode"
      :his-info="curInfo"
      :his-dialog-visible="hisDialogVisible"
      @refresh="fetchData"
      @myClose="closeEditDialog"
      @saveHis="saveHis"
    ></edit-dialog>
    <bind-checkroom-dialog
      :bind-info="curBindInfo"
      :bind-dialog-visible="bindDialogVisible"
      @myClose="closeBindDialog"
    ></bind-checkroom-dialog>
    <import-preview
      :visible.sync="previewVisible"
      :import-data.sync="importData"
      :hospital-code="formData.hospitalCode"
      @refresh="search"
    ></import-preview>
    <SetExamNotice
      :dialog-visible-set-exam-notice.sync="examNoticeVisible"
      :ids="multipleSelection"
      :hospital-code="formData.hospitalCode"
      @refresh="search"
    />
    <SetItemProperty
      :dialog-visible-item-property.sync="itemPropertyVisible"
      :ids="multipleSelection"
      :hospital-code="formData.hospitalCode"
      @refresh="search"
    />
    <SetCheckGroup
      :dialog-visible-check-group.sync="checkGroupVisible"
      :ids="multipleSelection"
      :hospital-code="formData.hospitalCode"
      :depart-code="formData.dep"
      @refresh="search"
    />
    <SetWorkOutType
      :dialog-visible-work-count-type.sync="workCountTypeVisible"
      :ids="multipleSelection"
      :hospital-code="formData.hospitalCode"
      @refresh="search"
    />
    <SetPartModality
      :dialog-visible-part-modality.sync="partModalityVisible"
      :ids="multipleSelection"
      :hospital-code="formData.hospitalCode"
      @refresh="search"
    />
    <SetTemplatePart
      :dialog-visible-template-part.sync="templatePartVisible"
      :ids="multipleSelection"
      :hospital-code="formData.hospitalCode"
      :dep="formData.dep.join(',')"
      :modality="formData.modality.join(',')"
      @refresh="search"
    />
  </div>
</template>
<script>
import {
  getCheckRoomList,
  getModalityTypeList,
  getDepList,
  postHisRegisterpartGetadvancepages,
  updateHisRegister,
  addHisRegister,
  getItemGroupList,
  deleteHisRegister
} from '@/api/api.js'
import paginationCont from '@/components/Pagination/index'
import HospDepFilter from '@/components/treeFilter/hospitalDepTree'
import hisPartSort from '@/components/appConfig/check/hisPartSort'
import { Options } from '@/utils/constant'
import { PageStatus } from '@/utils/constant'
// import { dateFormatter } from '@/utils/validate'
import { getCheckGroupList } from '@/api/api.js'
import editDialog from './editDialog'
import bindCheckroomDialog from './bindCheckroomDialog'
import SetExamNotice from './setExamNotice'
import SetItemProperty from './setItemProperty'
import SetCheckGroup from './setCheckGroup'
import SetWorkOutType from './setWorkOutType'
import SetPartModality from './setPartModality'
import SetTemplatePart from './setTemplatePart'
import importPreview from './importPreview'
import xlsx from 'xlsx'
import bus from '@/api/bus.js'

export default {
  name: 'ScheduleTemp',
  components: {
    paginationCont,
    editDialog,
    bindCheckroomDialog,
    importPreview,
    HospDepFilter,
    SetExamNotice,
    SetItemProperty,
    SetCheckGroup,
    SetWorkOutType,
    hisPartSort,
    SetPartModality,
    SetTemplatePart
  },
  data() {
    return {
      configVisible: false,
      pageStatus: PageStatus,
      that: this,
      options: Options,
      depArea: [],
      dep: [],
      department: [],
      modality: [],
      checkRoom: [],
      week: [],
      importData: [], // 导入的预览数据
      previewVisible: false,
      multipleSelection: [],
      formData: {
        hospitalCode: '',
        // depArea: [],
        dep: [],
        checkGroup: '',
        modality: [],
        checkRoom: [],
        checkClass: '',
        bigpart: '',
        smallpart: '',
        filterType: null, // 过滤类型:0不过滤、1过滤;-1全部
        partType: null, // 部位类型:0默认部位、1省对照部位;-1全部
        workCountType: null, // 系数类型:0未设置、1已设置;-1全部
        itemProperty: '', // 项目属性
        examNoticeGroup: '' // 注意事项组
      },
      depAreaOptions: [], // 影像区域
      departmentOptions: [], // 科室
      depOptions: [], // 检查部门
      modalityOptions: [], // 设备类型
      checkRoomOptions: [], // 检查机房
      checkGroupOptions: [], // 检查分组
      checkClassOptions: [],
      partTypeOptions: [
        { label: '默认部位', value: 0 },
        { label: '省对照部位', value: 1 }
      ],
      filterTypeOptions: [
        { label: '不过滤', value: 0 },
        { label: '过滤', value: 1 }
      ],
      workCountTypeOptions: [
        { label: '未设置', value: 0 },
        { label: '已设置', value: 1 }
      ],
      itempropertyOptions: [], // 项目属性
      examNoticeGroupOptions: [], // 注意事项
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      hisData: [],
      detailTable: [],
      curStatus: '',
      hisDialogVisible: false,
      bindDialogVisible: false,
      checkGroupVisible: false,
      loading: false,
      showToolBox: false,
      tableData: [
        // {
        //   checkroom: 'ct1',
        //   label: '星期一',
        //   total: 0, // 总号源数
        //   nodes: [
        //     {
        //       label: '', // 当前时段名称
        //       startTime: '', // 开始时间
        //       endTime: '', // 介绍时间
        //       startNum: 1, // 当前时段起始号源
        //       number: 0 // 号源数
        //     }
        //   ]
        // }
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      // editStatus: false, //编辑状态
      addOrEdit: 0, // 0 展示 1添加 2编辑
      curId: '',
      curTemp: {},
      curParamsTable: [],
      filtersFromDialog: [], // 从模板列表中获取的过滤条件列表
      ruleConditionOptions: [], // 数据字典数据
      curInfo: {}, // 当前编辑的行
      curBindInfo: {},
      fields: [
        // { label: '上午班', prop: 'appo' }
      ],
      columnlist: [
        { name: '机房', value: 'checkroom' }
      ],
      spanArr: {
        checkroom: []
      },
      pos: {
        WARDNO: []
      },
      // 快速查询
      quickFilterStatus: true,

      // 设置注意事项
      examNoticeVisible: false,
      // 项目属性
      itemPropertyVisible: false,
      // 批量设置
      workCountTypeVisible: false,
      // 批量设置部位设备
      partModalityVisible: false,
      // 批量设置词库模板部位
      templatePartVisible: false
    }
  },
  watch: {
    multipleSelection(val) {
      if (val && val.length > 0) {
        this.showToolBox = true
      } else {
        this.showToolBox = false
      }
    }
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    device() {
      return this.$store.state.app.device
    }
  },
  created() {
    this.$getHospitalList()
    // this.init()
  },
  async mounted() {
    this.formData.hospitalCode = this.$store.state.user.hospitalCode || ''
    try {
      this.getItempropertyOptions()
      this.getItemGroupOptions()
      this.getScheduledDepOptions()
      this.getModalityOptions()
      this.getCheckRoomOptions()
      setTimeout(() => {
        this.getCheckRoomList()
      }, 1000)
    } catch (err) {
      console.log(err)
    }
    this.$nextTick(() => {
      this.$refs.hospDepFilter && this.$refs.hospDepFilter.init()
    })
  },
  methods: {
    async checkGroupChange() {
      if (this.formData.checkGroup) {
        await this.getCheckRoomList()
        this.initData()
      } else {
        this.tableData = []
      }
    },
    // 机房分组（检查分组）
    getCheckGroupList() {
      const params = {
        hospitalCode: this.formData.hospitalCode,
        dep: this.formData.dep.join(',')
      }
      return new Promise(resolve => {
        getCheckGroupList(params).then(res => {
          if (res && res.code === 10000) {
            this.checkGroupOptions = res.content.list
            if (this.checkGroupOptions.length) {
              // this.formData.checkGroup = this.checkGroupOptions[0]
              // this.checkGroupChange()
              // resolve(res)
            }
            resolve(res)
          }
        })
      })
    },
    closeRight() {
      this.closeEditDialog()
      this.closeBindDialog()
    },
    init() {
      this.formData.hospitalCode = this.$store.state.user.hospitalCode || ''
      this.handleChange('hospital')
    },
    getItempropertyOptions() {
      /* 项目属性列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        Type: '项目属性'
      }
      return new Promise(resolve => {
        getItemGroupList(params).then((res) => {
          if (res.code === 10000) {
            this.itempropertyOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getItemGroupOptions() {
      /* 数据字典下项目列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        Type: '注意事项'
      }
      return new Promise(resolve => {
        getItemGroupList(params).then((res) => {
          if (res.code === 10000) {
            this.examNoticeGroupOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getScheduledDepOptions() {
      /* 检查部门列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode
        // depArea: this.formData.depArea.join(',')
      }
      return new Promise((resolve) => {
        getDepList(params).then((res) => {
          if (res.code === 10000) {
            this.depOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getModalityOptions() {
      /* 设备类型列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        // depArea: this.formData.depArea.join(','),
        dep: this.formData.dep.join(',')
      }
      return new Promise((resolve) => {
        getModalityTypeList(params).then((res) => {
          if (res.code === 10000) {
            this.modalityOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    appoNumberChange(index) {
      let t = 0
      this.fields.forEach(fld => {
        t = t + this.tableData[index][fld.prop] * 1
      })
      this.tableData[index].total = t
    },
    // 获取周数据
    getWeekData() {
      const weekLabel = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
      const resData = []
      weekLabel.forEach(item => {
        const ro = {
          week: item,
          total: 0
        }
        this.fields.forEach(f => {
          ro[`${f.prop}`] = ''
        })
        resData.push({ ...ro })
      })
      return resData
    },
    initData() {
      const weekData = this.getWeekData()
      console.log('weekData', weekData)
      const dls = []
      this.checkroomList.forEach(cs => {
        weekData.forEach(wdItem => {
          const _obj = {
            checkroom: cs,
            ...wdItem
          }
          dls.push(_obj)
        })
      })
      // console.log('tableData ===', dls)
      this.tableData = dls

      if (this.tableData.length > 0) {
        for (let i = 0; i < this.columnlist.length; i++) {
          this.getSpanArr(this.tableData, this.columnlist[i].value)
        }
      }
    },
    // 获取机房列表，通过机房分组
    getCheckRoomList() {
      const params = {
        hospitalCode: this.formData.hospitalCode,
        // depArea: this.formData.depArea,
        dep: this.formData.dep.join(','),
        checkGroup: this.formData.checkGroup
      }
      return new Promise(async resolve => {
        await getCheckRoomList(params).then(res => {
          if (res && res.code === 10000) {
            this.checkroomList = res.content.list
            resolve(res)
          }
        })
      })
    },
    getCheckRoomOptions() {
      /* 检查机房列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        // depArea: this.formData.depArea.join(','),
        dep: this.formData.dep.join(','),
        modalityType: this.formData.modality.join(',')
      }
      return new Promise((resolve) => {
        getCheckRoomList(params).then((res) => {
          if (res.code === 10000) {
            this.checkRoomOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    // 相同行的合并
    getSpanArr(data, column) {
      // 清空
      this.spanArr[column] = []
      this.pos[column] = []

      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr[column].push(1)
          this.pos[column] = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i][column] === data[i - 1][column]) {
            this.spanArr[column][this.pos[column]] += 1
            this.spanArr[column].push(0)
          } else {
            this.spanArr[column].push(1)
            this.pos[column] = i
          }
        }
      }
    },
    async handleChange(val) {
      this.closeRight()
      switch (val) {
        case 'hospital':
          this.itempropertyOptions = []
          this.examNoticeGroupOptions = []
          this.depOptions = []
          this.modalityOptions = []
          this.checkRoomOptions = []
          this.checkGroupOptions = []
          this.formData.dep = []
          this.formData.modality = []
          this.formData.checkRoom = []
          this.formData.checkGroup = []
          this.hisData = []
          this.totalCount = 0

          try {
            this.getScheduledDepOptions()
            this.getModalityOptions()
            this.getCheckRoomOptions()
            this.getCheckGroupList()
            this.getItempropertyOptions()
            this.getItemGroupOptions()
            this.search()
          } catch (err) {
            console.log(err)
          }
          this.$nextTick(() => {
            this.$refs.hospDepFilter && this.$refs.hospDepFilter.init()
          })
          break
        case 'dep':
          this.modalityOptions = []
          this.checkRoomOptions = []
          this.formData.modality = []
          this.formData.checkRoom = []
          this.checkGroupOptions = []
          this.formData.checkGroup = []
          try {
            await this.getModalityOptions()
            this.getCheckRoomOptions()
            this.getCheckGroupList()
            this.$refs.hospDepFilter && this.$refs.hospDepFilter.reset()
          } catch (err) {
            console.log(err)
          }
          break
        case 'modality':
          this.checkRoomOptions = []
          this.formData.checkRoom = []
          this.checkGroupOptions = []
          this.formData.checkGroup = []
          try {
            this.getCheckRoomOptions()
            this.getCheckGroupList()
            this.$refs.hospDepFilter && this.$refs.hospDepFilter.reset()
          } catch (err) {
            console.log(err)
          }
          break
        default:
          break
      }
    },
    search() {
      this.currentPage = 1
      this.fetchData()
    },
    fetchData() {
      if (!this.formData.hospitalCode) {
        this.$message.warning('请选择医院')
        return
      }
      this.loading = true
      let params = {
        ...this.formData,
        dep: this.formData.dep.join(','),
        itemProperty: this.formData.itemProperty.join(','),
        modality: this.formData.modality.join(','),
        checkRoom: this.formData.checkRoom.join(','),
        partType: typeof this.formData.partType === 'number' ? this.formData.partType : -1, // 省对照部位
        filterType: typeof this.formData.filterType === 'number' ? this.formData.filterType : -1, // 过滤
        workCountType: typeof this.formData.workCountType === 'number' ? this.formData.workCountType : -1, // 系数类型
        pageSize: this.pageSize,
        pageNumber: this.currentPage
      }
      params.checkGroup = params.checkGroup.join(',')
      postHisRegisterpartGetadvancepages(params)
        .then(async (res) => {
          this.loading = false
          if (res && res.code === 10000) {
            this.hisData = res.content.list
            params.pageSize = this.totalCount = res.content.totalCount
            bus.$emit('hisIndexInfo', params)
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    bindCheckRoom(i, row) {
      this.$refs.table.setCurrentRow(row)
      this.curBindInfo = row
      this.bindDialogVisible = true
      this.hisDialogVisible = false
    },
    handleEdit(i, row) {
      this.$refs.table.setCurrentRow(row)
      this.curInfo = row
      this.hisDialogVisible = true
      this.$nextTick(() => {
        this.$refs.editRoom.init(row)
      })
      this.bindDialogVisible = false
      this.curStatus = this.pageStatus.edit
    },
    // 获取右边form
    getRightPanel() {
      this.hisDialogVisible = true
      this.bindDialogVisible = false
      this.curStatus = this.pageStatus.add
      this.clearRuleForm()
      this.$nextTick(() => {
        this.$refs.editRoom.init()
      })
    },
    upload(file) {
      return new Promise((resolve) => {
        let reader = new FileReader()
        reader.readAsBinaryString(file)
        reader.onload = (ev) => {
          resolve(ev.target.result)
        }
      })
    },
    downLoadExcel() {
      var a = document.createElement('a')
      a.download = 'HIS数据导入模板.xlsx'
      a.href = '/static/file/HIS数据导入模板.xlsx'
      let body = document.getElementsByTagName('body')[0]
      body.appendChild(a) // 修复firefox中无法触发click
      a.click()
      body.removeChild(a)
    },
    async importExcel(ev) {
      // 导入Excel数据
      let file = ev.raw
      if (!file) return
      let reader = await this.upload(file)

      const worker = xlsx.read(reader, { type: 'binary' })
      // 这个是将数据进行一步拼接
      //  worker.Sheets[worker.SheetNames[0]]
      // 将返回的数据转换为json对象的数据
      reader = xlsx.utils.sheet_to_json(worker.Sheets[worker.SheetNames[0]])
      try {
        let hisRegisterparts = reader.map((item) => {
          return {
            hospitalCode: this.formData.hospitalCode + '',
            dep: item.检查部门 ? item.检查部门 + '' : '',
            modality: item.设备类型 ? item.设备类型 + '' : '',
            bigpart: item.大部位 ? item.大部位 + '' : '',
            bigpartEn: item.大部位英文 ? item.大部位英文 + '' : '',
            smallpart: item.小部位 ? item.小部位 + '' : '',
            smallpartEn: item.小部位英文 ? item.小部位英文 + '' : '',
            templatePart: item.模板部位 ? item.模板部位 + '' : '',
            itemCode: item.部位编码 ? item.部位编码 + '' : '',
            examNoticeGroup: item.注意事项组 ? item.注意事项组 + '' : '',
            itemProperty: item.项目属性 ? item.项目属性 + '' : '',
            workCount: item.系数 ? item.系数 + '' : '',
            filter: item.是否过滤检查项目 === '过滤' || item.是否过滤检查项目 === '是' ? '过滤' : '',
            partType: item.是否省对照部位 === '是' ? 1 : 0,
            uisId: item.超声部位代码 ? item.超声部位代码 + '' : '',
            hisid: item.HIS部位代码 ? item.HIS部位代码 + '' : '',
            itemName: item.省互认项目名称 ? item.省互认项目名称 + '' : ''
          }
        })
        this.importData = hisRegisterparts
        this.previewVisible = true
      } catch (error) {
        console.error(error)
        this.$message({
          type: 'warning',
          message: '解析文件失败，请检查导入数据'
        })
      }
    },
    handleDelete(i, row) {
      let confirmMsg = '此操作将永久删除该条检查项目, 是否继续?'
      if (this.curInfo && this.curInfo.id === row.id) {
        confirmMsg = '该条检查项目正在编辑, 是否删除?'
      }
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteData(row)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deleteData(row) {
      deleteHisRegister({ id: row.id, hospitalCode: row.hospitalCode }).then(
        (res) => {
          if (res.code === 10000) {
            this.$message.success('删除成功')
            this.hisDialogVisible = false
            this.bindDialogVisible = false
            this.fetchData()
          }
        }
      )
    },
    clearRuleForm() {
      this.curInfo = {
        hospitalCode: this.formData.hospitalCode,
        id: '',
        examNotice: '',
        workCount: '',
        filter: '',
        dep: '',
        modality: '',
        bigpart: '',
        bigpartEn: '',
        smallpart: '',
        smallpartEn: '',
        templatePart: '',
        itemCode: ''
      }
      //   this.$refs.editRoom.handleReset()
      //   this.$refs.editRoom.$refs.form && this.$refs.editRoom.$refs.form.clearValidate()
    },
    closeEditDialog() {
      this.hisDialogVisible = false
      this.clearRuleForm()
      //   this.curInfo = {}
    },
    closeBindDialog() {
      this.bindDialogVisible = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    saveHis(val, addFlag) {
      this.$refs.editRoom.$refs.form.validate((valid, object) => {
        if (valid) {
          let data = {
            ...val,
            workCount: val.workCount.toString(),
            filter: val.filter ? val.filter : ''
          }
          if (data.itemProperty && Array.isArray(data.itemProperty)) {
            data.itemProperty = data.itemProperty.join(',')
          }
          if (data.checkGroup && Array.isArray(data.checkGroup)) {
            data.checkGroup = data.checkGroup.join(',')
          }
          if (this.curStatus === this.pageStatus.edit && !addFlag) {
            updateHisRegister(data).then((res) => {
              if (res && res.code === 10000) {
                this.$message.success('修改成功')
                this.fetchData()
                this.closeEditDialog()
                if (!this.itempropertyOptions.includes(data.itemProperty)) {
                  this.getItempropertyOptions()
                }
              }
            })
          } else {
            addHisRegister(data).then((res) => {
              if (res && res.code === 10000) {
                this.closeEditDialog()
                if (addFlag) {
                  this.$message.success(
                    '新增成功，当前编辑部位为：' + val.bigpart
                  )
                  this.curInfo = res.content
                } else {
                  this.$message.success('新增成功')
                  this.clearRuleForm()
                }
                this.fetchData()
                if (!this.itempropertyOptions.includes(data.itemProperty)) {
                  this.getItempropertyOptions()
                }
              }
            })
          }
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 100)
          for (let k in object) {
            this.$message.warning(object[k][0].message)
            return
          }
        }
      })
    },
    // 格式化医院code
    frtHospCode(row, column, cellValue, index) {
      let name = ''
      let hospIndex = this.mx_hospitalList.findIndex(
        (item) => item.code === cellValue
      )
      if (hospIndex !== -1) {
        name = this.mx_hospitalList[hospIndex].name
      }
      return name
    },
    batchDelete() {
      // 批量删除
      let confirmMsg = '此操作将永久批量删除选中HIS部位, 是否继续?'
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            let successNum = 0
            let faliNum = 0
            for (let v of this.multipleSelection) {
              let data = {
                hospitalCode: v.hospitalCode,
                id: v.id
              }
              await deleteHisRegister(data).then((res) => {
                if (res && res.code === 10000) {
                  successNum++
                } else {
                  faliNum++
                }
              })
            }
            this.search()
            this.$message.success(
              `已经成功删除` + successNum + '条,失败' + faliNum + '条'
            )
          } catch (error) {
            console.error(error)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 设置注意事项字典组
    setExamNoticeGroup() {
      this.examNoticeVisible = true
    },
    // 设置项目属性字典组
    setItemPropertyVisible() {
      this.itemPropertyVisible = true
    },
    // 设置项目属性字典组
    setCheckGroupVisible() {
      this.checkGroupVisible = true
    },
    // 设置部位系数字典组
    setWorkOutTypeVisible() {
      this.workCountTypeVisible = true
    },
    // 设置部位设备
    setPartModality() {
      this.partModalityVisible = true
    },
    // 设置部位设备
    setTemplatePart() {
      this.templatePartVisible = true
    },
    cancleChoose() {
      // 取消选择
      this.multipleSelection = []
      this.$refs.table.clearSelection()
    },
    // 快速查询返回
    treeChange(data) {
      let dep = data.dep
      let modality = data.modality
      console.log('data===>1111111', data)
      let depChange = this.formData.dep.length === 1 && this.formData.dep[0] !== dep
      this.formData.dep = dep ? [dep] : []
      this.formData.modality = modality ? [modality] : []
      this.formData.checkRoom = []
      this.checkGroupOptions = []
      this.formData.checkGroup = []
      if (depChange) {
        this.getModalityOptions()
        this.getCheckRoomOptions()
        this.getCheckGroupList().then(() => {
          this.search()
        }).catch((error) => {
          console.error('Error in getCheckGroupList:', error)
        })
      } else {
        this.checkGroupOptions = []
        this.getModalityOptions()
        this.getCheckRoomOptions()
        this.getCheckGroupList().then(() => {
          this.search()
        }).catch((error) => {
          console.error('Error in getCheckGroupList:', error)
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.edit-table {
  .el-select {
    width: 82px;
  }
  .el-input-number {
    width: 102px;
  }
  .el-date-editor {
    width: 182px;
  }
}
.small-input {
  /deep/ .el-input__inner {
    width: 208px;
  }
}
.content-title {
  margin-left:4px;
  margin-bottom: 16px;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
  .tit {
    margin-right: 20px;
  }
  .add-button {
    width: 96px;
    height: 32px;
  }
}
.span-click {
  color: #00C0EF;
  cursor: pointer;
  font-weight: 500 !important;
}
.toolBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #e5e7ec;
  padding: 12px 28px;
  position: fixed;
  bottom: 0;
  background: #fff;
  z-index: 10;
  margin-left: -20px;
  .toolBox-text {
    margin-left: 8px;
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.65);
    span {
      margin: 0 4px;
    }
  }
  .cancle-click {
    cursor: pointer;
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #00C0EF;
    margin-left: 32px;
  }
}
.toolBox-small {
  width: calc(100% - 210px);
}
.toolBox-midul {
  width: calc(100% - 54px);
}
.toolBox-large {
  width: 100%;
}
.col-left {
  padding: 15px;
}
.icon {
  margin-right: 4px;
}
.blue-color {
  color: #00C0EF;
}
</style>
